#!/usr/bin/python
# -*- coding:utf-8 -*-
from urllib import parse,request
import datetime
import base64
import hmac
import hashlib
import json
import urllib
def get_current_date():
    date = datetime.datetime.strftime(datetime.datetime.utcnow(), "%a, %d %b %Y %H:%M:%S GMT")
    return date

def to_md5_base64(strBody):
    hash = hashlib.md5()
    d = strBody.encode('utf-8')
    hash.update(d)
    return hash.hexdigest().strip()

def to_sha1_base64(stringToSign, secret):
    ss = secret.encode('utf-8')
    sign = stringToSign.encode('utf-8')
    hmacsha1 = hmac.new(ss, sign, hashlib.sha1)
    return base64.b64encode(hmacsha1.digest())

ak_id = '<用户的AK_ID>'
ak_secret = '<用户的AK_SECRET>'
options = {
    'url': '<请求的url>',
    'method': 'POST',
    'headers': {
        'accept': 'application/json',
        'content-type': 'application/json',
        'date':  get_current_date(),
        'authorization': ''
    }
}
# options = {
#     'url': '<请求的url>',
#     'method': 'GET',
#     'headers': {
#         'accept': 'application/json',
#         'content-type': 'application/json',
#         'date': get_current_date(),  # 'Sat, 07 May 2016 08:19:52 GMT',  # get_current_date(),
#         'authorization': ''
#     }
# }

def ali_send(url, key, sct, data):
    options['url'] = url
    ak_id = key
    ak_secret = sct
    body = data
    bodymd5 = ''
    if not body == '':
        bodymd5 = to_md5_base64(body)
    print("bodymd5: ", bodymd5)
    urlPath = parse.urlparse(options['url'])
    if urlPath.query != '':
        urlPath = urlPath.path + "?" + urlPath.query
    else:
        urlPath = urlPath.path
    bodymd5str = str(bodymd5)
    stringToSign = options['method'] + '\n' + options['headers']['accept'] + '\n' + bodymd5str[2:len(bodymd5str)-1] + '\n' + options['headers']['content-type'] + '\n' + options['headers']['date'] + '\n' + urlPath
    signature = to_sha1_base64(stringToSign, ak_secret)
    print("signto string: ", stringToSign)
    signaturestr = str(signature)
    authHeader = 'Dataplus ' + ak_id + ':' + signaturestr[2:len(signaturestr) -1]
    options['headers']['authorization'] = authHeader
    print("authHeader: ", authHeader)

    method = options['method']
    url = options['url']
    print("method: ", method)
    print("url : ", url)
    if 'GET' == method or 'DELETE' == method:
        req = request.Request(url)
    elif 'POST' == method or 'PUT' == method:
        bodybyte = body.encode('utf-8')
        req = request.Request(url, bodybyte)
    req.get_method = lambda: method
    for key, value in options['headers'].items():
        req.add_header(key, value)

    print(options)

    conn = request.urlopen(req)
    response = conn.read()
    return response